﻿using System.Text;

namespace UtilLibrary.FileTool
{
    public class FileHelper
    {
        /// <summary>
        /// 下载文件并显示下载进度
        /// </summary>
        /// <param name="url"></param>
        /// <param name="localPath"></param>
        /// <returns></returns>
        public async Task DownloadFileAsync(string url, string localPath)
        {
            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
            {
                using (Stream stream = await response.Content.ReadAsStreamAsync())
                {
                    using (FileStream fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        long totalBytesRead = 0;
                        long totalBytes = response.Content.Headers.ContentLength ?? -1;

                        while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead);
                            totalBytesRead += bytesRead;
                            // 处理下载进度，例如更新UI
                            Console.WriteLine($"下载进度：{totalBytesRead}/{totalBytes}");

                            float result = totalBytesRead / (float)totalBytes * 100;

                            var aaa = Math.Round(result, 2);

                            //LogHelper.Debug($"下载进度：{totalBytesRead}/{totalBytes}  {Math.Round(result,2)}%");
                        }
                    }
                }
            }

        }
        #region 创建文件夹
        public static void CreateDirectory(string filepath)
        {
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
        }
        #endregion 创建文件夹

        #region 创建文本文件

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        public static void CreateFile(string path, string content = "")
        {
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path)!);
            }
            if (!string.IsNullOrWhiteSpace(content))
            {
                using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
                {
                    sw.Write(content);
                }
            }
        }

        #endregion 创建文本文件
    }
}
